from cart.cart import Cart
from order.models import OrderItem


class Order(object):

    """ Заказ пользователя """

    def __init__(self, request):

        self.user_cart = Cart(request)


    def add(self, created_order):

        """ Добавляем заказ пользователя """

        self.add_coupon(created_order)

        for item in self.user_cart:
            OrderItem.objects.create(order=created_order,
                                     product=item['product'],
                                     price=item['price'],
                                     quantity=item['quantity'])
        self.user_cart.clean()


    def add_coupon(self, created_order):

        """ Добавляем купон к корзине если он есть """

        if self.user_cart.coupon:
            created_order.coupon = self.user_cart.coupon
            created_order.discount = self.user_cart.coupon.discount
            created_order.save()
